package com.whu.assignment8.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whu.assignment8.common.Result;
import com.whu.assignment8.entity.User;
import com.whu.assignment8.security.JwtTokenUtil;
import com.whu.assignment8.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Resource
    private IUserService userService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @GetMapping("")
    @PreAuthorize("hasAuthority('user/query')")
    public Result findAllUser(){
        return Result.success(userService.list());
    }


    @PostMapping
    @PreAuthorize("hasAuthority('user/update')")
    public Result save(@RequestBody User user){
        return Result.success(userService.saveOrUpdate(user));
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('user/update')")
    public Result deleteUser(@PathVariable String userName){
        return  Result.success(userService.removeById(userName));
    }


    @GetMapping("/{userName}")
    @PreAuthorize("hasAuthority('user/query') or #userName == authentication.name")
    public Result getUser(@PathVariable String userName){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",userName);
        return Result.success(userService.getOne(queryWrapper));
    }

    @PatchMapping("/changePassword/{userName}")
    @PreAuthorize("hasAuthority('Administration') or #userName == authentication.name")
    public void changePassword(@PathVariable String userName, String password){
        userService.changePassword(userName,password);
    }


    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user){
        authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()));
        final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getName());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(token);
    }

}
